package se.haaga.jsupervision.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class PropertiesReader {
	
	private static PropertiesReader instance = null;
	
	private Map<String, String> translations = null;
	
	private static String LANG_FOLDER = "./etc/lang/";
	
	private String selectLanguage = null;
 	
	private PropertiesReader() {
		translations = readAllTranslations();
	}
	
	public String getLanguageTranslation(String key) {
		String translation = translations.get(key);
		if (translation == null) {
			return key;
		} else {
			return translation;
		}
	}
	
	private Map<String, String> readAllTranslations() {
		Map<String, String> returnMap = new HashMap<String, String>();
		List<String> files = getAvailableLanguageFiles();
		for (String file : files) {
			String lang = file.replaceAll(".properties", "");
			try {
			    BufferedReader in = new BufferedReader(new FileReader(LANG_FOLDER + file));
			    String str;
			    while ((str = in.readLine()) != null) {
			    	if (!(str.startsWith("#") || str.equals(""))) { // Don't read empty lines or comments
			    		String key = str.split(" = ")[0];
				    	String value = str.split(" = ")[1];
				        returnMap.put(lang + "." + key, value);
			    	}
			    }
			    in.close();
			} catch (IOException e) {
				System.err.println(e);
			}
		}
		return returnMap;
	}

	public static PropertiesReader getInstance() {
		if (instance == null) {
			instance = new PropertiesReader();
		}
		return instance;
	}
	
	@Override
	protected Object clone() throws CloneNotSupportedException {
		throw new CloneNotSupportedException(); // No cloning here
	}
	
	public List<String> getAvailableLanguages() {
		List<String> availableLanguages = new LinkedList<String>();
		List<String> files = getAvailableLanguageFiles();
		for (String file : files) {
			availableLanguages.add(file.replaceAll(".properties", ""));
		}
		return availableLanguages;
	}
	
	private List<String> getAvailableLanguageFiles() {
		List<String> availableLanguageFiles = new LinkedList<String>();
		File langDir = new File(LANG_FOLDER);
		String[] files = langDir.list(new FilenameFilter() {
			@Override
			public boolean accept(File dir, String name) {
				return !name.startsWith(".");
			}
		});
		for (String file : files) {
			availableLanguageFiles.add(file);
		}
		return availableLanguageFiles;
	}
	
	private String getDefaultLanguage() {
		return "english"; // FIXME Prop this
	}

	public void setSelectLanguage(String selectLanguage) {
		this.selectLanguage = selectLanguage;
	}

	public String getSelectLanguage() {
		if (selectLanguage == null) {
			selectLanguage = getDefaultLanguage();
		}
		return selectLanguage;
	}

}
